//
//  KFCartVC.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/8.
//

#import "KFCartVC.h"
#import "KFRealCartVC.h"
#import "KFLoginVC.h"
#import "BaseNavVC.h"
@interface KFCartVC ()
@property(nonatomic, strong) NSArray *dataList;
@property(nonatomic, strong) UIView *inputView;
@property(nonatomic, strong) UITextField *inputTF;
@property(nonatomic, strong) UIButton *curBtn;
@property(nonatomic, strong) UIScrollView *bgScro;
// .h 文件
@property (nonatomic, strong) NSArray *groupedDataArray;
@property(nonatomic, assign) NSInteger titleLabClickCount;
@end

@implementation KFCartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *def =[NSUserDefaults standardUserDefaults];
    if ([[def objectForKey:@"ipDomain"] isEqualToString:@"http://43.138.162.50:1300"] ) {
        self.myTitle = @"桌台";
    }else{
        self.myTitle = @"桌台(测试版)";
    }
    
    [self.titleLab addTarget:self action:@selector(titleLabClick)];
}
-(void)titleLabClick{
    self.titleLabClickCount ++;
    NSString * count = [NSString stringWithFormat:@"%ld",self.titleLabClickCount];
    XHQHUDText(count);
    if (self.titleLabClickCount == 3) {
        NSUserDefaults *def =[NSUserDefaults standardUserDefaults];
        [def setObject:nil forKey:@"userInfo"];
        [Mytools deleteAllUserDefaules];
        dispatch_async(dispatch_get_main_queue(), ^{
            KFLoginVC * vc = [[KFLoginVC alloc]init];
            BaseNavVC * nav = [[BaseNavVC alloc]initWithRootViewController:vc];
            [UIApplication sharedApplication].delegate.window.rootViewController = nav;
        });
    }
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}
-(void)getData{
    XHQHUDInView(self.view);
    [PGNetworkHelper GET:[WorkUrl returnURL:Interface_For_Board_List] parameters:nil cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            self.dataList = responseObject[@"data"];
            if (_bgScro) {
                for (UIView *v  in self.bgScro.subviews) {
                    if (v.tag >= 300) {
                        [v removeFromSuperview];
                    }
                }
                [self resetTable];
            }else{
                [self createUI];
            }
        }else{
            XHQHUDErrorText(responseObject[@"msg"]);
        }
        [self.bgScro.mj_header endRefreshing];
        XHQHUDHide();
    } failure:^(id error) {
        XHQHUDHide();
    }];
}
-(void)createUI{
    self.bgScro = [[UIScrollView alloc]initWithFrame:Frame(0 , kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT - kTopHeight-kTabbarHeight)];
    [self.view addSubview:self.bgScro];
    __weak typeof(self)weakSelf = self;
    self.bgScro.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf getData];
    }];
    [self resetTable];
}
-(void)resetTable{
    CGFloat btnW = 0;
    CGFloat leftRight = 0;
    CGFloat vMarin = 0;
    if ([Mytools getIsIpad]) {
        btnW = (SCREEN_WIDTH - 180)/5;
        leftRight = 50;
        vMarin = 20;
    }else{
        btnW = (SCREEN_WIDTH - 20)/5;
        leftRight = 20;
        vMarin = 10;
    }
    NSInteger btnH = btnW;
   
    UIButton * lastBtn = nil;
    
    // 创建分组数组（增加户外分组）
    NSMutableArray *arr1 = [NSMutableArray new];  // 桌
    NSMutableArray *arr2 = [NSMutableArray new];  // 吧
    NSMutableArray *arr3 = [NSMutableArray new];  // 土和意（土在前，意在后）
    NSMutableArray *arr4 = [NSMutableArray new];  // 户外
    NSMutableArray *arr5 = [NSMutableArray new];  // 其他（保留原有结构）
    
    // 收集所有土和意到临时数组
    NSMutableArray *soilArray = [NSMutableArray new];
    NSMutableArray *meaningArray = [NSMutableArray new];
    
    for (int i=0; i<self.dataList.count; i++) {
        NSDictionary *dic = self.dataList[i];
        NSString *boardName = dic[@"boardName"];
        
        if ([boardName containsString:@"桌"]) {
            [arr1 addObject:dic];
        } else if ([boardName containsString:@"吧"]) {
            [arr2 addObject:dic];
        } else if ([boardName containsString:@"土"]) {
            [soilArray addObject:dic];
        } else if ([boardName containsString:@"意"]) {
            [meaningArray addObject:dic];
        } else if ([boardName containsString:@"户"]) { // 新增户外处理
            [arr4 addObject:dic];
        } else {
            [arr5 addObject:dic]; // 其他未分类项
        }
    }
    
    // 合并土和意到arr3
    [arr3 addObjectsFromArray:soilArray];
    [arr3 addObjectsFromArray:meaningArray];
    
    // 更新分组数组（包含户外分组）
    self.groupedDataArray = @[arr1, arr2, arr3, arr4, arr5];
    
    for (int i=0; i<self.groupedDataArray.count; i++) {
        NSMutableArray * array = self.groupedDataArray[i];
        for (int j =0; j<array.count; j++) {
            NSDictionary *dic = array[j];
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = Frame(leftRight+(j%5)*(btnW+vMarin), leftRight+i*(btnH+leftRight), btnW, btnH);
            btn.backgroundColor = UIColor.whiteColor;
            btn.borderColor = UIColor.blackColor;
            btn.borderWidth = 1;
            [btn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
            [btn setTitle:dic[@"boardName"] forState:UIControlStateNormal];
            btn.titleLabel.font = UIFontMake(17);
            btn.tag = 300+10*i+j;
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.cornerRadius = btnW/2;
            [self.bgScro addSubview:btn];
            lastBtn = btn;
            
        }
    }
    self.bgScro.contentSize = CGSizeMake(SCREEN_WIDTH, CGRectGetMaxY(lastBtn.frame)+20);
}
-(void)btnClick:(UIButton*)sender{
    NSInteger tag = sender.tag - 300;

    // 计算分组索引和分组内的索引
    NSInteger section = tag / 10;  // 分组索引 (i)
    NSInteger index = tag % 10;    // 分组内的索引 (j)

    // 确保分组索引有效
    if (section < self.groupedDataArray.count) {
        NSArray *sectionArray = self.groupedDataArray[section];
        
        // 确保分组内的索引有效
        if (index < sectionArray.count) {
            NSDictionary *b = sectionArray[index];
            // 现在可以使用data进行操作
            KFRealCartVC *vc = [KFRealCartVC new];
            vc.boardId = b[@"id"];
            vc.isCreate = YES;
            vc.dinnerCount = @"1";
            vc.backBlock = ^{
                self.tabBarController.selectedIndex = 1;
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    
}
-(void)cancelBtnClick{
    [self.inputView removeFromSuperview];
    self.inputView = nil;
}
-(void)certainBtnClick{
//    [self cancelBtnClick];
}


@end
